package sample;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DbUtil {

    private static String mysqlDriver = "com.mysql.cj.jdbc.Driver";
    public static Connection getConnection(String driver, String url, String username, String password) {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static Connection getMySQLConnection(String url, String username, String password) {
        return getConnection(mysqlDriver, url, username, password);
    }
    public static void closeAll(Connection conn, PreparedStatement preparedStatement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void closeAll(Connection conn, ResultSet resultSet) {
        closeAll(conn, null, resultSet);
    }
    public static void closeAll(Connection conn, PreparedStatement preparedStatement) {
        closeAll(conn, preparedStatement, null);
    }
    public static int executeUpdate(Connection conn, String sql, Object[] params) {
        int result = 0;
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    preparedStatement.setObject(i + 1, params[i]);
                }
            }
            result = preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, preparedStatement);
        }
        return result;
    }
    public static int executeUpdate(Connection conn, String sql) {
        return executeUpdate(conn, sql, null);
    }
    public static ResultSet executeQuery(Connection conn, String sql, Object[] params) {
        ResultSet result = null;
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    preparedStatement.setObject(i + 1, params[i]);
                }
            }
            result = preparedStatement.executeQuery();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static ResultSet executeQuery(Connection conn, String sql) {
        return executeQuery(conn, sql, null);
    }
}